JavaScript's event loop manages two distinct task queues: the microtask queue and the macrotask (callback) queue. The microtask queue handles high-priority, short operations that need to be executed immediately after the current operation completes, before any rendering or new macrotasks. The macrotask queue handles lower-priority, longer operations that are executed in rounds, with the event loop taking one macrotask per iteration. The critical difference is that microtasks are processed in a single batch until the queue is empty, whereas macrotasks are processed one at a time, with the event loop potentially rendering the page between them. This ordering is fundamental to understanding JavaScript's asynchronous behavior and avoiding subtle bugs.
Also known as: Task queue, callback queue, event queue
Sources: setTimeout, setInterval, setImmediate (Node.js), I/O operations, UI rendering, message events, requestAnimationFrame
Processing model: One macrotask is taken from the queue per event loop iteration
Priority: Lower priority than microtasks
Browser rendering: May occur between macrotasks
Order: Tasks are executed in FIFO (First In, First Out) order
Also known as: Job queue, microtask queue
Sources: Promise callbacks (then, catch, finally), queueMicrotask, MutationObserver, process.nextTick (Node.js)
Processing model: All microtasks are processed until the queue is empty before moving to the next macrotask
Priority: Higher priority than macrotasks
Browser rendering: Microtasks block rendering until the queue is empty
Potential issue: Recursively adding microtasks can cause infinite loops and freeze the page
Understanding the microtask/macrotask distinction is crucial for avoiding subtle bugs in asynchronous JavaScript. For example, Promise callbacks and queueMicrotask are processed before setTimeout even with a 0ms delay, which can lead to unexpected ordering. Additionally, while macrotasks allow the browser to render between them (keeping the UI responsive), microtasks can block rendering if they are continuously added, potentially causing performance issues. Modern JavaScript patterns like React's batching rely on microtasks to batch state updates efficiently before rendering.